/*
 * engine.cpp
 *
 *  Created on: Jan 12, 2011
 *      Author: dima
 */

#include "engine.h"

Engine* gEngine;
ResourceManager* gResourceManager;
Platform* gPlatform;
TextureManager* gTextureManager;
Renderer* gRenderer;

Engine::Engine()
{

	gPlatform = new Platform();
	gResourceManager = new ResourceManager();
	gTextureManager = new TextureManager();
	gRenderer = new Renderer();
}

Engine::~Engine()
{
	delete gRenderer;

	delete gTextureManager;
	delete gResourceManager;
	delete gPlatform;
}

void Engine::init()
{
	gPlatform->init();
	gRenderer->init();
	gResourceManager->init();
	gTextureManager->init();

	mRunning = true;


	pthread_create(&mUpdateThread, NULL, Engine::updateLoop, NULL);
	pthread_create(&mRenderThread, NULL, Engine::renderLoop, NULL);
}

void Engine::destroy()
{
	gRenderer->destroy();
	gPlatform->destroy();
}

int Engine::start()
{
	gEngine = new Engine();
	gEngine->init();
	gEngine->run();
	gEngine->destroy();
	delete gEngine;

	return 0;
}

void Engine::requestExit()
{
	mRunning.lock();
	mRunning = false;
	mRunning.unlock();
}

void Engine::run()
{
	// initialize engine

	pthread_join(mRenderThread,NULL);
}


void* Engine::renderLoop(void* )
{
	gRenderer->activateGLContext();

	while( gEngine->mRunning )
	{
		gRenderer->render();
	}

	gRenderer->deleteGLContext();
	return NULL;
}

void* Engine::updateLoop(void* )
{
	while( gEngine->mRunning )
	{
		if(gPlatform->processEvents())
		{
			gEngine->mRunning.lock();
			gEngine->mRunning = false;
			gEngine->mRunning.unlock();
			return NULL;
		}
		sleep(1);
	}

	return NULL;
}
